package cn.lili.modules.promotion.serviceimpl;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.modules.promotion.entity.dos.TicketPollRecord;
import cn.lili.modules.promotion.mapper.TicketPollRecordMapper;
import cn.lili.modules.promotion.service.TicketPollRecordService;
import cn.lili.modules.promotion.service.TicketPollService;
import cn.lili.modules.statistics.entity.enums.SearchTypeEnum;
import cn.lili.modules.statistics.util.StatisticsDateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TicketPollRecordServiceImpl extends ServiceImpl<TicketPollRecordMapper, TicketPollRecord>
        implements TicketPollRecordService {

    private final TicketPollService ticketPollService;


    /**
     * 获取用户当天投票数据
     * @return
     */
    @Override
    public List<TicketPollRecord> getByUserId () {
        Date[] dates = StatisticsDateUtil.getDateArray(SearchTypeEnum.TODAY);
        LambdaQueryWrapper<TicketPollRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TicketPollRecord::getUserId, UserContext.getCurrentId());
        queryWrapper.between(TicketPollRecord::getCreateTime, dates[0], dates[1]);
        return this.list(queryWrapper);
    }


    /**
     * 用户投票
     * @param pollId 投票嘉宾ID
     */
    @Override
    public void add (String pollId) {
        if (StringUtils.isEmpty(pollId)) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        List<TicketPollRecord> ticketPollRecordList = getByUserId();
        if (ticketPollRecordList.size() >= 3) {
            throw new ServiceException("每人每天只能投3票");
        }
        TicketPollRecord ticketPollRecord = new TicketPollRecord();
        ticketPollRecord.setUserId(UserContext.getCurrentId());
        ticketPollRecord.setPollId(pollId);
        ticketPollRecord.setId(SnowFlake.getIdStr());
        this.save(ticketPollRecord);

        ticketPollService.addPoll(pollId, 1);

    }
}
